package com.xuhf.basic;

import com.xuhf.config.Config;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

public class Consumer1 {

    public static void main(String[] args) throws Exception {
        // 1、创建一个拉取消息的消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(Config.CONSUMER_GROUP);
        // 2、设置名字地址C
        consumer.setNamesrvAddr(Config.NAMESRV_ADDR);
        // 3、指定从哪里开始消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        // 4、绑定消息的主题
        consumer.subscribe(Config.TOPIC, "*");
        consumer.setConsumeThreadMin(2);
        consumer.setConsumeThreadMin(5);
        consumer.setConsumeMessageBatchMaxSize(1);
        // 5、消费者监听处理消息方法
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    String f = String.format("获取消息长度：%d, 消息tag：%s , 消息体：%s", msgs.size(), msg.getTags(), new String(msg.getBody()));
                    System.out.println(f);
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 6、启动消费者
        consumer.start();
    }
}
